<template>
  <div style="width:100%">
    <div v-if="isInChildren">
      <div v-for="item in valueArray" :key="item.id" class="wps_container">
        <div class="left">{{ item.name }}</div>
      </div>
    </div>
    <div v-else-if="isDesigner" class="wps_container">
      <el-select class="left">
        <el-option
          label="default"
          value="default">
        </el-option>
      </el-select>
      <el-button type="primary" plain class="ml-5">
        创建文件
      </el-button>
      <el-button type="primary" plain class="ml-5">
        上传文件
      </el-button>
    </div>
    <div v-else-if="!value" class="wps_container">
      <el-select v-if="uploadMethods === 'create'" v-model="fileType" placeholder="请选择" :disabled="!mixEditable" @change="selectType" class="left">
        <el-option
          v-for="(item, index) in typeOptions"
          :key="index"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button v-if="uploadMethods === 'create'" type="primary" :disabled="!mixEditable" plain @click="creatApp">
        创建文件
      </el-button>
      <el-upload
        v-else
        ref="upload"
        v-bind="$attrs"
        :disabled="!mixEditable"
        :headers="headers"
        listType="button"
        :http-request="uploadFile"
        :on-success="success"
        :on-error="error"
        v-on="$listeners"
        :show-file-list="false"
      >
        <el-button plain type="primary">上传文件</el-button>
      </el-upload>
    </div>
    <div v-else-if="value">
      <div v-for="item in valueArray" :key="item.id" class="wps_container">
        <div class="left">{{ item.name }}</div>
        <el-button type="primary" plain @click="previewApp(item)" :disabled="!mixEditable">
          预览
        </el-button>
        <el-button type="primary" plain @click="editApp(item)" :disabled="!mixEditable">
          编辑
        </el-button>
        <el-button v-if="isSwitchOfd" type="primary" plain @click="switchOfd(item)" :disabled="!mixEditable">
          转ofd
        </el-button>
      </div>
    </div>
    <pm-dialog
        title="转换ofd格式"
        :visible.sync="dialogVisiable"
        width="700"
        :close-on-click-modal="false"
        :showFullScreenButton="true"
        append-to-body
        :showFooter="false"
        :before-close="handleClose"
      >
        <div style="text-align: center;padding: 20px;">
          <el-button type="primary" @click="previewOfd">预览</el-button>
          <el-button type="primary">
            <a :href="downloadUrl" >下载</a>
          </el-button>
        </div>
    </pm-dialog>
  </div>
</template>
<script>
import routerContextPath from '../../mixins/router-context-path.js'
export default {
  name:'wps',
  mixins: [routerContextPath],
  props:{
    // fieldid,name,type
    value:'',
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    headers: {
      default: () => {},
    },
    isInChildren: {
      type: Boolean,
      default: false
    },
    fileName: {
      type: String,
      default: 'demo'
    },
    // 转ofd显示与否
    isSwitchOfd: {
      type: Boolean,
      default: false
    },
    // 创建文件方式
    uploadMethods: {
      type: String,
      default: 'create'
    }
  },
  computed: {
    valueArray() {
      const arr = this.value && this.value.split(',').map(i => {
        const obj = i.split('/')
        return {
          id: obj[0],
          name: obj[1],
          type: obj[2]
        }
      }) || []
      console.log(arr,'==arr')
      return arr
    },
    typeOptions() {
      return this.options && this.options.filter(item => item.value !== 'f')
    },
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    dispatchProxy(){
      if (Vue.prototype.dispatchProxy) {
        return Vue.prototype.dispatchProxy(this)
      } else {
        return this.dispatch
      }
    },
  },
  data() {
    return {
      options: [{
        label: '文字文件 (word)',
        value: 'w',
        types: ['doc' , 'dot' , 'wps' , 'wpt' , 'docx' , 'dotx' , 'docm' , 'dotm']
      }, {
        label: '表格文件 (excel)',
        value: 's',
        types: ['xls' , 'xlt' , 'et' , 'xlsx' , 'xltx' , 'xlsm' , 'xltm']
      }, {
        label: '演示文件 (ppt)',
        value: 'p',
        types: ['ppt' , 'pptx' , 'pptm' , 'ppsx' , 'ppsm' , 'pps' , 'potx' , 'potm' , 'dpt' , 'dps']
      }, {
        label: 'PDF文件',
        value: 'f',
        types: ['pdf']
      }],
      fileType: 'w',
      ofdId: '',
      downloadUrl: '',
      dialogVisiable: false
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val && val.indexOf('/') === -1) {
          this.getFieldInfo(val)
        }
      }
    }
  },
  created(){
    // console.log(WebOfficeSDK,'WebOfficeSDK')
    console.log(this.$attrs,'this.$attrs')
    // const jssdk = WebOfficeSDK.config({
    //   url: 'https://wwo.wps.cn/office/p', // 该地址需要对接方服务端提供，形如 https://wwo.wps.cn/office/p/xxx
    //   // 更多配置参数...
    // })

    // jssdk.on('fileOpen', (data) => {
    //   console.log('打开文档成功: ', data)
    // })
  },
  methods: {
    async getFieldInfo(val) {
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.AttachmentController.getAttachment, {
        attachmentId: val
      })
      if (!resp.error) {
        const { fileId, fileName, fileType} = resp.data
        const type = (this.options.find(o => o.types.includes(fileType)) || {}).value || 'other'
        const val = fileId + '/' + fileName + '/' + type
        this.$emit('input', val)
      }
    },
    async creatApp() {
      const user = localStorage.getItem('user')
      let resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.createLink, {
        fileName: this.fileName,
        type: this.fileType,
        userName: JSON.parse(user).userName
      })
      if (!resp.error) {

        const { id, name } = resp.data[0]
        this.$message.success(`创建成功${name || ''}`)
        const val = id + '/' + name + '/' + this.fileType
        this.$emit('input', val)
        this.$emit('addFile', resp.data[0])
        // this.editApp({
        //   id: fileId,
        //   type
        // })
      } else {
        this.$message.error(resp.error)
      }
    },
    async previewApp(item) {
      const user = localStorage.getItem('user')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkView, {
        fileId: item.id,
        type: item.type || 'w',
        wThirdParams: JSON.parse(user).userName
      })
      const { msg, data, code } = resp.data
      if (code === 200) {
        // this.setToken(data.link)
        window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=preview`)
        // window.open(data.link)
      } else {
        this.$message.error(msg)
      }
    },
    async editApp(item) {
      const user = localStorage.getItem('user')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkEdit, {
        fileId: item.id,
        type: item.type || 'w',
        wThirdParams: JSON.parse(user).userName
      })
      const { msg, data, code } = resp.data
      if (code === 200) {
        window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=edit`)
      } else {
        this.$message.error(msg)
      }
    },
    selectType(append) {
      
    },
    async uploadFile(file){
      let params=new FormData()
      const user = localStorage.getItem('user')
      params.append('attachments',file.file)
      params.append('userName', JSON.parse(user).userName)
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.XFFileController.fileUpload, params)
      if (!resp.error && resp.data) {
        const { id, name } = resp.data[0]
        const fileType = name.slice(name.lastIndexOf('.') + 1)
        const type = (this.options.find(o => o.types.includes(fileType)) || {}).value || 'other'
        const val = id + '/' + name + '/' + type
        this.$emit('input', val)
        this.$emit('addFile', resp.data[0])
        this.fileList = []
        this.$message({
            type: 'success',
            message: '上传成功!'
        })
      }
    },
    async switchOfd(item) {
      // const prefix = 'http://121.36.242.165:28084'
      const prefix = window.location.origin
      let params = new FormData()
      params.append('taskId',  String(Math.random()*100000000).slice(0,7))
      params.append('docFilename', item.name)
      params.append('docUrl', `${prefix}/XFfileServer/fileDownload?id=${item.id}`)
      params.append('target', 'ofd')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.convertFile, params)
      const { msg, data, code } = resp.data
      if (code === 200) {
        await this.downloadFormat(data)
      } else {
        this.$message.error(msg)
      }
    },
    // 根据id下载
    // downloadself(item) {
    //   // AjaxUtil.config.responseType = "blob";
    //   AjaxUtil.ajax({
    //     responseType : 'blob',
    //     // url: window.location.origin + `/XFfileServer/fileDownload?id=${fileId}`,
    //     url: `/XFfileServer/fileDownload?id=${fileId}`,
    //     method: 'GET',
    //     data: {},
    //   }).then(resp => {
    //   console.log(resp,'=======下载resp')
    //       let url = window.URL.createObjectURL(resp.data);  //生成文件流下载链接
    //       let a = document.createElement('a');      //创建一个a标签用来跳转
    //       a.href = url;                             // a标签 href  赋值 链接  
    //       a.download = fileName;                  //设置下载文件的文件名和文件格式
    //       document.body.appendChild(a);             //将标签DOM，放置页面
    //       a.click();                              
    //       window.URL.revokeObjectURL(url);     //释放 url 对象内存
    //       document.body.removeChild(a);
    //   })
    //   AjaxUtil.config.responseType = "json";
    // },
    async downloadFormat(item) {
      const { downloadId, routerKey } = item
      const user = localStorage.getItem('user')
      const data = {
        downloadId,
        routeKey: routerKey,
        userName: JSON.parse(user).userName,
        target: 'ofd',
        fileName: this.fileName
      }
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.operateDocumentResultDownload, data)
      if (!resp.error) {
        this.downloadUrl = resp.data.downloadUrl
        this.ofdId = resp.data.fileId
        this.openAction()
      }
    },
    openAction() {
      this.dialogVisiable = true
    },
    previewOfd() {
      this.previewApp({
        id: this.ofdId,
        type: 'f'
      })
    },
    handleClose() {
      this.dialogVisiable = false
    },
    error(err, file, fileList) {
      this.$emit('uploadError',{err, file, fileList})
    },
    success(response, file, fileList) {

    },
  }
}
</script>
<style lang="scss" scoped>
  .wps_container {
    display: flex;
    .left {
      flex: 1;
    }
    .el-button {
      margin-left: 5px;
    }
  }
  a {
    text-decoration: none;
    color: #fff;
  }
  a:link {
    color: #fff;
  }
  a:hover {
    color: #fff;
  }
</style>